<template>
  <div>
    <a-upload :show-upload-list="false" :customRequest="upload" name="avatar" list-type="picture-card"
      class="avatar-uploader">
      <img v-if="img" :src="img" class="avatar" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import API from './../api'

defineProps(['img'])

const emit = defineEmits(['update:img'])

const loading = ref(false)

const upload = async (file) => {
  loading.value = true
  // 拿到要上传的文件

  // 转成formData 对象
  const formData = new FormData()

  formData.append('files', file.file)
  formData.append('isdev', 'qf')

  // 给后端传过去

  const data = await API.uploadImg(formData)

  // 拿到返回的图片url地址
  
  // 双向绑定数据
  emit('update:img', data.url)
  loading.value = false
}


</script>

<style scoped>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.avatar {
  width: 100%;
  height: 100%;
}
</style>